<template>
  <div class="main-container">
    <div class="header">
      <div style="display: flex; align-items: center;">
        <el-icon size="24" style="margin-right: 10px;"><Monitor /></el-icon>
        <h2>设备管理系统</h2>
      </div>
      <div style="display: flex; align-items: center;">
        <span style="margin-right: 15px;">欢迎，{{ username }}</span>
        <el-button type="text" @click="handleLogout" style="color: white;">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </div>
    
    <div class="content">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>Modbus配置列表 - 二级设备: {{ subDeviceInfo.subDeviceId }}</h3>
        <div>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加Modbus配置
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button @click="handleBack">
            <el-icon><ArrowLeft /></el-icon>
            返回二级设备列表
          </el-button>
        </div>
      </div>
      
      <el-table :data="deviceKeys" border stripe v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="keyNumber" label="编号" width="80" />
        <el-table-column prop="keyName" label="上报Key名称" width="150" />
        <el-table-column prop="slaveAddress" label="从站地址" width="100" />
        <el-table-column prop="operationType" label="读/写" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.operationType === 1 ? 'success' : 'warning'">
              {{ scope.row.operationType === 1 ? '读' : '写' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="functionCode" label="功能码" width="120">
          <template #default="scope">
            <span>{{ getFunctionCodeText(scope.row.functionCode) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="functionValue" label="功能值" width="100" />
        <el-table-column prop="registerStartAddress" label="起始地址" width="100" />
        <el-table-column prop="registerCount" label="读取数量" width="100" />
        <el-table-column prop="byteOrder" label="字节顺序" width="100">
          <template #default="scope">
            <span>{{ getByteOrderText(scope.row.byteOrder) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="multiplier" label="倍率" width="80" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="warning" size="small" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div style="display: flex; justify-content: space-between; margin-top: 20px;">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'DeviceKeyList',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const loading = ref(false)
    const username = ref(sessionStorage.getItem('username') || '')
    const subDeviceId = ref(route.params.subDeviceId)
    const deviceKeys = ref([])
    const selectedRows = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const subDeviceInfo = ref({})

    const loadDeviceKeys = async () => {
      try {
        loading.value = true
        const token = sessionStorage.getItem('token')
        const response = await axios.get(`/api/device-keys/sub-device/${subDeviceId.value}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          deviceKeys.value = response.data.data
          total.value = response.data.data.length
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('加载Modbus配置列表失败')
      } finally {
        loading.value = false
      }
    }

    const loadSubDeviceInfo = async () => {
      try {
        const token = sessionStorage.getItem('token')
        const response = await axios.get(`/api/sub-devices/${subDeviceId.value}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          subDeviceInfo.value = response.data.data
        }
      } catch (error) {
        console.error('加载二级设备信息失败')
      }
    }

    const handleAdd = () => {
      router.push(`/device-keys/${subDeviceId.value}/add`)
    }

    const handleEdit = (deviceKey) => {
      router.push(`/device-keys/edit/${deviceKey.id}`)
    }

    const handleDelete = async (deviceKey) => {
      try {
        await ElMessageBox.confirm('确定要删除这个Key表单吗？', '警告', {
          type: 'warning'
        })
        
        const token = sessionStorage.getItem('token')
        const response = await axios.delete(`/api/device-keys/${deviceKey.id}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          ElMessage.success('删除成功')
          loadDeviceKeys()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }

    const handleBatchDelete = async () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的Modbus配置')
        return
      }
      
      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个Modbus配置吗？`, '警告', {
          type: 'warning'
        })
        
        const token = sessionStorage.getItem('token')
        const ids = selectedRows.value.map(row => row.id)
        const response = await axios.delete('/api/device-keys/batch', {
          data: ids,
          headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }
        })
        
        if (response.data.success) {
          ElMessage.success('批量删除成功')
          loadDeviceKeys()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }

    const handleBack = () => {
      if (subDeviceInfo.value.mainDeviceImei) {
        router.push(`/devices/config/${subDeviceInfo.value.mainDeviceImei}`)
      } else {
        router.push('/devices')
      }
    }

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      currentPage.value = 1
      loadDeviceKeys()
    }

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      loadDeviceKeys()
    }

    const getByteOrderText = (byteOrder) => {
      const byteOrderMap = {
        1: '大端',
        2: '小端',
        3: '中端',
        4: '混合端'
      }
      return byteOrderMap[byteOrder] || '未知'
    }

    const getFunctionCodeText = (functionCode) => {
      const functionCodeMap = {
        1: '读线圈状态',
        2: '读离散输入状态',
        3: '读保持寄存器',
        4: '读输入寄存器',
        5: '写单个线圈',
        6: '写单个保持寄存器',
        7: '写多个线圈',
        8: '写多个保持寄存器'
      }
      return functionCodeMap[functionCode] || '未知'
    }

    const handleLogout = () => {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('username')
      router.push('/login')
    }

    onMounted(() => {
      loadSubDeviceInfo()
      loadDeviceKeys()
    })

    return {
      loading,
      username,
      subDeviceId,
      deviceKeys,
      selectedRows,
      currentPage,
      pageSize,
      total,
      subDeviceInfo,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSelectionChange,
      handleBatchDelete,
      handleBack,
      handleSizeChange,
      handleCurrentChange,
      getByteOrderText,
      getFunctionCodeText,
      handleLogout
    }
  }
}
</script>

<style scoped>
.main-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  color: white;
  padding: 15px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.content {
  padding: 30px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>